import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class HttpPage extends StatefulWidget {
  HttpPage({Key key}) : super(key: key);

  @override
  _HttpPageState createState() => _HttpPageState();
}

class _HttpPageState extends State<HttpPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // Map userInfo = {"username": "张三", "age": 20};
    // var a = json.encode(userInfo); //Map转json字符串
    // print(userInfo is Map);
    // print(a is String);

    // String userInfo = '{"username": "张三", "age": 20}';
    // Map user = json.decode(userInfo);
    // print(user["username"]);
  }

  _getdata() async {
    var url = "http://xnsj1.zdlian.cn/api/no_token/banner_shift_list";
    var response = await http.get(url);
    if (response.statusCode == 200) {
      var jsonResponse = jsonDecode(response.body);
      List mList = jsonResponse["info"]["rows"];
      for (var i = 0; i < mList.length; i++) {
        print(mList[i]["name"]);
      }
      // var itemCount = jsonResponse['totalItems'];
      // print('Number of books about http: $itemCount.');
    } else {
      print('Request failed with status: ${response.statusCode}.');
    }
  }

  _postData() async {
    var url = "http://xnsj1.zdlian.cn/api/no_token/banner_shift_list";
    var response = await http.post(url, body: {"name": "张三"});
    if (response.statusCode == 200) {
      response.body; //服务器返回值
      // var itemCount = jsonResponse['totalItems'];
      // print('Number of books about http: $itemCount.');
    } else {
      print('Request failed with status: ${response.statusCode}.');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Scaffold(
        appBar: AppBar(
          title: Text("Http请求"),
        ),
        body: Column(
          children: [
            RaisedButton(
              child: Text("Get请求"),
              onPressed: this._getdata,
            ),
            RaisedButton(
              child: Text("Post请求"),
              onPressed: () {},
            ),
            RaisedButton(
              child: Text("Get请求数据，渲染数据演示demo"),
              onPressed: () {
                Navigator.pushNamed(context, '/dioHttpDemo');
              },
            )
          ],
        ),
      ),
    );
  }
}
